package parse

import (
	"github.com/PuerkitoBio/goquery"
	"github.com/gookit/color"
	"net/http"
	"regexp"
	"strconv"
	"strings"
)

type DoubanMovie struct {
	Title string `json:"title"`
	Subtitle string `json:"subtitle"`
	Other string `json:"other"`
	Desc string `json:"desc"`
	Year string `json:"year"`
	Area string `json:"area"`
	Tag string `json:"tag"`
	Star string `json:"star"`
	Comment string `json:"comment"`
	Quote string `json:"quote"`
}

type Page struct {
	Page int
	Url string
}

//获取分页
func GetPages(url string)[]Page  {
	resp, err := http.Get(url)
	if err != nil {
		color.Error.Print(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode !=200 {
		color.Error.Print("status code error: %d %s ", resp.StatusCode, resp.Status)
	}

	document, err := goquery.NewDocumentFromReader(resp.Body)
	if err!=nil{
		color.Error.Print(err)
	}

	return ParsePage(document)
}

//分析分页
func ParsePage(doc *goquery.Document) (pages[]Page){
	pages = append(pages, Page{Page: 1, Url: ""})

	doc.Find("#content > div > div.article > div.paginator > a").Each(func(i int, s *goquery.Selection) {
		page, _ := strconv.Atoi(s.Text())
		url,_:= s.Attr("href")

		pages = append(pages, Page{
			Page: page,
			Url:  url,
		})
	})
	return pages
}

//分析电影数据
func ParseMovies(doc *goquery.Document)(movies []DoubanMovie){
	doc.Find("#content > div > div.article > ol > li").Each(func(i int, s *goquery.Selection) {
		title := s.Find(".hd a span").Eq(0).Text()
		subtitle := s.Find(".hd a span").Eq(1).Text()
		subtitle = strings.TrimLeft(subtitle, "  / ")

		other := s.Find(".hd a span").Eq(2).Text()
		other = strings.TrimLeft(other, "  / ")

		desc := strings.TrimSpace(s.Find(".bd p").Eq(0).Text())
		DescInfo := strings.Split(desc, "\n")
		desc = DescInfo[0]

		movieDesc := strings.Split(DescInfo[1], "/")
		year := strings.TrimSpace(movieDesc[0])
		area := strings.TrimSpace(movieDesc[1])
		tag := strings.TrimSpace(movieDesc[2])

		star := s.Find(".bd .star .rating_num").Text()

		comment := strings.TrimSpace(s.Find(".bd .star span").Eq(3).Text())
		compile := regexp.MustCompile("[0-9]")
		comment = strings.Join(compile.FindAllString(comment, -1), "")

		quote := s.Find(".quote .inq").Text()

		movie := DoubanMovie{
			Title:    title,
			Subtitle: subtitle,
			Other:    other,
			Desc:     desc,
			Year:     year,
			Area:     area,
			Tag:      tag,
			Star:     star,
			Comment:  comment,
			Quote:    quote,
		}

		color.Info.Printf("i: %d,movie: %v\n",i,movie)
		movies = append(movies, movie)
	})
	return movies
}